package sealte.port.scanner.run;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.TreeSet;

public class PortScanner2 {
	private static String ip = "127.0.0.1";
	private static TreeSet<Integer> data = new TreeSet<Integer>();
	private static int maxport = 65535;
	private static int maxThread = 100; //recommended value
	private static InetAddress hostAddress;
	private static int iport = 0;
	private static long startTime;
	
	public static void main(String[] args) throws Throwable{
		ip = args.length >= 1 ? args[0]:ip;
		maxport = args.length >= 2 ? Integer.parseInt(args[1]):maxport;
		maxThread = args.length >= 3 ? Integer.parseInt(args[2]):maxThread;
		
		System.out.println("Start...");
		startTime = System.currentTimeMillis();
		hostAddress = InetAddress.getByName(ip);
		if(maxport > 65535) maxport = 65535;
		for(int i=0;i<=maxThread;i++){
			startThread();
		}
	}
	
	private static Thread startThread(){
		Thread t = new Thread(new Runnable(){
			public void run(){
				int port;
				while((port = getIport()) <= maxport){
					try{
						System.out.println("Scanning port:" + port);
						Socket socket = new Socket(hostAddress,port);
						System.out.println(hostAddress + ":" + port + " Open!");
						data.add(port);
						socket.close();
					}catch(IOException e){
						
					}
					if(port == maxport){
						System.out.println("Total:########################################");
						String portList = "";
						int flag = 0;
						for(int i:data){
							portList += i;
							flag++;
							if(flag<data.size()){
								portList += "-";
							}
						}
						System.out.println(portList);
						System.out.println("Cost total time : " + (System.currentTimeMillis() - startTime) + "ms");
						System.out.println("End.");
					}
				}
			}
		});
		t.start();
		return t;
	}
	
	public static synchronized int getIport(){
		return ++iport;
	}
}
